﻿namespace VolleyballHall
{
    using System;
    using Microsoft.Xna.Framework;

    public class Camera
    {

        float yaw; // obrót względem osi z (kąty RPY)
        
        float pitch; //obrót względem osi y (kąty RPY)

        const float dYaw = MathHelper.Pi / 40;

        const float dPitch = MathHelper.Pi / 40;


        public Vector3 Position { get; private set; }

        public Vector3 LookAt { get; private set; }

        public Vector3 Up { get; private set; }

        public Matrix CreateViewMatrix()
        {
            return Matrix.CreateLookAt(Position, Position + LookAt, Up);
        }

        public Camera()
        {
            Position = Vector3.Zero;
            yaw = 0;
            pitch = 0;
            Update();

        }

        public Camera(Vector3 pos, float y, float p)
        {
            Position = pos;
            yaw = y;
            pitch = p;
            Update();

        }

        private void Update()
        {
            float x, y, z;

            x = (float)(Math.Sin(yaw) * Math.Cos(pitch));
            y = (float)(Math.Cos(yaw) * Math.Cos(pitch));
            z = (float)(Math.Sin(pitch));

            LookAt = new Vector3(x, y, z);

            x = (float)(Math.Sin(yaw) * Math.Cos(pitch + MathHelper.PiOver2));
            y = (float)(Math.Cos(yaw) * Math.Cos(pitch + MathHelper.PiOver2));
            z = (float)(Math.Sin(pitch + MathHelper.PiOver2));

            Up = new Vector3(x, y, z);


        }

        public void RotateUp()
        {
            pitch += dPitch;
            pitch = Math.Min(pitch, MathHelper.PiOver2);
            Update();
        }

        public void RotateDown()
        {
            pitch -= dPitch;
            pitch = Math.Max(pitch, -MathHelper.PiOver2);
            Update();
        }

        public void RotateLeft()
        {
            yaw -= dYaw;
            if (yaw < 0)
                yaw += MathHelper.TwoPi;
            Update();
        }

        public void RotateRight()
        {
            yaw += dYaw;
            if (yaw >= MathHelper.TwoPi)
                yaw -= MathHelper.TwoPi;
            Update();
        }

        public void MoveUp()
        {
            Position += LookAt;
        }

        public void MoveDown()
        {
            Position -= LookAt;
        }

        public void MoveLeft()
        {
            Position += Vector3.Cross(Up, LookAt);
        }

        public void MoveRight()
        {
            Position -= Vector3.Cross(Up, LookAt);
        }
    }
}
